package com.yu.core.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.alibaba.fastjson.JSONObject;
import com.baidu.ueditor.ActionEnter;
import com.baidu.ueditor.define.MultiState;
import com.baidu.ueditor.define.State;
import com.google.common.collect.Maps;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.upload.UploadFile;
import com.stonehenge.backend.tools.StaticToolit;
import com.stonehenge.backend.tools.data.DataFactory;
import com.yu.model.Config;
import com.yu.model.Invitation;
import com.yu.model.Order;
import com.yu.model.User;
import com.yu.util.PicUtil;
import com.yu.util.QiniuComponent;
import com.yu.util.SendPostMethod;
import com.yu.util.UuidUtil;

import edu.npu.fastexcel.ExcelException;
import edu.npu.fastexcel.FastExcel;
import edu.npu.fastexcel.Sheet;
import edu.npu.fastexcel.Workbook;

public class UtilController extends Controller {
	private String ueditUrl = "";

	/*
	 * 上传文件
	 */
	public void uploadFile() {
		JSONObject json = new JSONObject();
		String fileName ="";
		try {
			System.out.println(PathKit.getWebRootPath());
//			UploadFile file = getFile("pic", PathKit.getWebRootPath() + "\\temp");
//			File source = file.getFile();
			UploadFile file = getFile(); 
			File source = file.getFile();
			fileName = file.getFileName();
			// 后缀
			String extension = fileName.substring(fileName.lastIndexOf("."));
			fileName = UuidUtil.get32Id() + extension;
			/*
			 * String prefix; if(".png".equals(extension) ||
			 * ".jpg".equals(extension) || ".gif".equals(extension)){ prefix =
			 * "img"; }else{ prefix = "file"; }
			 */

			FileInputStream fis = new FileInputStream(source);
			File targetDir = new File(PathKit.getWebRootPath() + "/temp");
			if (!targetDir.exists()) {
				targetDir.mkdirs();
			}
			File target = new File(targetDir, fileName);
			if (!target.exists()) {
				target.createNewFile();
			}
			FileOutputStream fos = new FileOutputStream(target);
			byte[] bts = new byte[300];
			while (fis.read(bts, 0, 300) != -1) {
				fos.write(bts, 0, 300);
			}
			fos.close();
			fis.close();
			// 上传至7牛
			new PicUtil().upload(target.getAbsolutePath(), fileName);
			target.deleteOnExit();
		} catch (FileNotFoundException e) {
			json.put("error", 1);
			json.put("message", "上传出现错误，请稍后再上传");
		} catch (Exception e) {
			e.printStackTrace();
			json.put("error", 1);
			json.put("message", "文件写入服务器出现错误，请稍后再上传");
		}
		renderText(PicUtil.QINIU_DIR + fileName);
	}

	public void ueditor() {
		try {
			UploadFile file = getFile("pic", PathKit.getWebRootPath() + "/temp");
			File source = file.getFile();
			String orgFileName = source.getName();
			String fileName = file.getFileName();
			// 后缀
			String extension = fileName.substring(fileName.lastIndexOf("."));
			fileName = "ueditor_" + System.currentTimeMillis() + "_"
					+ UuidUtil.get32Id() + extension;
			try {
				FileInputStream fis = new FileInputStream(source);
				File targetDir = new File(PathKit.getWebRootPath() + "/temp");
				if (!targetDir.exists()) {
					targetDir.mkdirs();
				}
				File target = new File(targetDir, fileName);
				if (!target.exists()) {
					target.createNewFile();
				}
				FileOutputStream fos = new FileOutputStream(target);
				byte[] bts = new byte[300];
				while (fis.read(bts, 0, 300) != -1) {
					fos.write(bts, 0, 300);
				}
				fos.close();
				fis.close();
				// 上传至7牛
				new PicUtil().upload(target.getAbsolutePath(), fileName);
				source.delete();
			} catch (FileNotFoundException e) {

			} catch (IOException e) {

			}
			try {
				getRequest().setCharacterEncoding("utf-8");
				State state = new MultiState(true);
				state.putInfo("title", orgFileName);
				state.putInfo("url", PicUtil.QINIU_DIR + fileName);
				state.putInfo("type", "");
				state.putInfo("original", null);
				renderText(state.toJSONString());
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			try {
				getRequest().setCharacterEncoding("utf-8");
				getResponse().setHeader("Content-Type", "text/html");
				String rootPath = getRequest().getServletContext().getRealPath(
						"/");
				renderText(new ActionEnter(getRequest(), rootPath).exec());
			} catch (UnsupportedEncodingException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
		}
	}

	public void importOrder() {
		UploadFile file = getFile("pic", PathKit.getWebRootPath() + "/temp");
		File source = file.getFile();
		Workbook workBook = FastExcel.createReadableWorkbook(source);
		try {
			workBook.open();
			Sheet s = workBook.getSheet(0);
			for (int i = s.getFirstRow() + 1; i < s.getLastRow(); i++) {
				String name = "";
				String phone = "";
				String express = "";
				String membernumber = "";
				for (int j = s.getFirstColumn(); j < s.getLastColumn(); j++) {
					if (j == 3) {
						name = s.getCell(i, j);
					} else if (j == 4) {
						phone = s.getCell(i, j);
					} else if (j == 10) {
						membernumber = s.getCell(i, j);
					} else if (j == 11) {
						express = s.getCell(i, j);
					}
				}
				Order order = Order.dao
						.findFirst("select * from club_order where name ='"
								+ name
								+ "' and phone ='"
								+ phone
								+ "' and status > -1 and (LENGTH(express_no) < 1  or express_no is NULL )  order by createtime desc limit 1 ");
				if (order != null) {
					order.set("express", "申通快递");
					order.set("express_no", express);
					order.update();
				}
				User user = User.dao
						.findFirst("select * from club_users where phone ='"
								+ phone
								+ "' and (LENGTH(membernumber) < 1 or membernumber is NULL)  ");
				if (user != null) {
					user.set("membernumber", membernumber);
					user.update();
				}
			}
			workBook.close();
		} catch (ExcelException e) {
			e.printStackTrace();
		}
		source.delete();
		source.deleteOnExit();
		renderText("操作成功!");
	}

	/**
	 * 生成resid
	 * 
	 * @param map
	 * @return
	 */
	private String genResID(Map<String, Object> map) {
		String imagetype = (String) map.get("imagetype");
		String usingdir = (String) map.get("usingdir");
		long userid = 61034864334556L;
		String format = (String) map.get("format");
		if (StaticToolit.isEmpty(imagetype) || StaticToolit.isEmpty(usingdir)
				|| StaticToolit.isEmpty(format))
			return null;
		String resid = "";
		String fileName = DataFactory.newFileID(String.valueOf(userid),
				imagetype, usingdir); // 不包括后缀
		String fileFullName = fileName + "." + format; // 包括后缀
		if (!resid.isEmpty()) {// 如果已经设定
			if (resid.contains(".")) {
				fileName = resid.substring(0, resid.indexOf("."));
				fileFullName = resid;
			} else {
				fileFullName = resid + "." + format;
				fileName = resid;
			}
		}
		resid = fileFullName;// 确保带后缀
		return resid;
	}

	public void excel() {
		// 第一步，创建一个webbook，对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
		// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
		HSSFSheet sheet = wb.createSheet("学生表一");
		// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
		HSSFRow row = sheet.createRow((int) 0);
		// 第四步，创建单元格，并设置值表头 设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

		HSSFCell cell = row.createCell((short) 0);
		cell.setCellValue("项目名称");
		cell.setCellStyle(style);
		cell = row.createCell((short) 1);
		cell.setCellValue("项目描述");
		cell.setCellStyle(style);
		cell = row.createCell((short) 2);
		cell.setCellValue("创始人信息");
		cell.setCellStyle(style);
		cell = row.createCell((short) 3);
		cell.setCellValue("项目介绍");
		cell.setCellStyle(style);
		cell = row.createCell((short) 4);
		cell.setCellValue("市场前景");
		cell.setCellStyle(style);
		cell = row.createCell((short) 5);
		cell.setCellValue("竞争优势");
		cell.setCellStyle(style);
		cell = row.createCell((short) 6);
		cell.setCellValue("团队介绍");
		cell.setCellStyle(style);
		cell = row.createCell((short) 7);
		cell.setCellValue("上传时间");
		cell.setCellStyle(style);
		// 第五步，写入实体数据 实际应用中这些数据从数据库得到，
		/*
		 * List<Product> list = Product.createCriteria().list {
		 * eq("verifyStatus", Product.ProductType.VERIFY_RESULT_PASS) }
		 * 
		 * for (int i = 0; i < list.size(); i++) { row = sheet.createRow((int) i
		 * + 1); Product product = list.get(i) // 第四步，创建单元格，并设置值
		 * row.createCell((short) 0).setCellValue(product.title);
		 * row.createCell((short) 1).setCellValue(product.content);
		 * row.createCell((short)
		 * 2).setCellValue(product.fIntroduce?.replaceAll("<br/>", "\r\n"));
		 * row.createCell((short)
		 * 3).setCellValue(product.pIntroduce?.replaceAll("<br/>", "\r\n"));
		 * row.createCell((short)
		 * 4).setCellValue(product.market?.replaceAll("<br/>", "\r\n"));
		 * row.createCell((short)
		 * 5).setCellValue(product.edge?.replaceAll("<br/>", "\r\n"));
		 * row.createCell((short)
		 * 6).setCellValue(product.tIntroduce?.replaceAll("<br/>", "\r\n"));
		 * row.createCell((short)
		 * 7).setCellValue(DateUtil.commonDateFormat.format(product.dateCreated)
		 * );
		 * 
		 * }
		 */
		// 第六步，将文件存到指定位置
		try {
			// 获取网站部署路径(通过ServletContext对象)，用于确定下载文件位置，从而实现下载
			// String path = servletContext.getRealPath("/");
			HttpServletResponse response = getResponse();
			// 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
			response.setContentType("multipart/form-data");
			// 2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
			response.setHeader("Content-Disposition", "attachment;fileName="
					+ "product.xls");
			ServletOutputStream out;
			try {
				// 3.通过response获取ServletOutputStream对象(out)
				out = response.getOutputStream();
				wb.write(out);
				out.close();
				out.flush();

			} catch (IOException e) {
				e.printStackTrace();
			}

			/*
			 * FileOutputStream fout = new FileOutputStream("E:/product.xls");
			 * wb.write(fout); fout.close();
			 */
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
